package camera;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import sun.misc.BASE64Encoder;


/**
 *
 * @author pedro
 */
public class MainFrame extends javax.swing.JFrame {

    private String urlCtrl = "http://admin:Traumata@192.168.2.90:80/pantiltcontrol.cgi";
    private String urlImage = "http://192.168.2.90:80/image/jpeg.cgi";
    private int pan = 5;
    private int tilt = 5;
    private final HiloFoto foto = new HiloFoto( this );
    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
    }
    
    private void sendPost( int pan, int tilt, int type) throws MalformedURLException, IOException {
        String authString = "admin:Traumata";
        URL camera = new URL( urlCtrl );
        URLConnection uCon = camera.openConnection();
        uCon.setRequestProperty( "Authorization", "Basic " + 
                new BASE64Encoder().encode( authString.getBytes() ) );

        HttpURLConnection con = (HttpURLConnection) uCon;
        con.setRequestMethod( "POST" );
        con.setRequestProperty( "Content-Type", 
           "application/x-www-form-urlencoded" );
        con.setRequestProperty("Content-Language", "en-US"); 
        
        String urlParams = "PanSingleMoveDegree=" + pan;
        urlParams += "&TiltSingleMoveDegree=" + tilt;
        urlParams += "&PanTiltSingleMove=" + type;
        con.setRequestProperty( "Content-Length", "" + 
               Integer.toString( urlParams.getBytes().length ) );
        con.setUseCaches (false);
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream( con.getOutputStream() );
        wr.writeBytes( urlParams );
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        // System.out.println( "Código devuelto: " + responseCode );
        con.disconnect();
        getImage();
    }
    
    public void getImage() throws MalformedURLException, IOException {
        String authString = "visor1:visor1";
        URL camera = new URL( urlImage );
        URLConnection uCon = camera.openConnection();
        uCon.setRequestProperty( "Authorization", "Basic " + 
                new BASE64Encoder().encode( authString.getBytes() ) );

        HttpURLConnection con = (HttpURLConnection) uCon;
        // System.out.println( con.getContentType() );
        int responseCode = con.getResponseCode();
        // System.out.println( "Código devuelto: " + responseCode );
        
        InputStream is = con.getInputStream();
        File tmpFile = File.createTempFile( "camera", ".jpg" );
        FileOutputStream fout = new FileOutputStream( tmpFile );
        
        byte[] buffer = new byte[ 1000 ];
        int leidos = is.read( buffer );
        while ( leidos > 0 ) {
            fout.write( buffer, 0, leidos );
            leidos = is.read( buffer );
        }
        is.close();
        fout.close();
        ImageIcon img = new ImageIcon( tmpFile.getAbsolutePath() );
        resizeImage( img, lblImage);
        lblImage.setText( "" );

        con.disconnect();
        tmpFile.delete();
    }
    
    private static ImageIcon resizeImage( ImageIcon imgSrc, JLabel lbl) {
        int width = lbl.getWidth();
        int height = lbl.getHeight();
        ImageIcon bi = new ImageIcon();
        Graphics2D g2d = (Graphics2D) lbl.getGraphics();
        g2d.addRenderingHints(new RenderingHints( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY ) );
        g2d.drawImage( imgSrc.getImage(), 0, 0, width, height, null );
        g2d.dispose();
        return bi;
    }
    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pumImage = new javax.swing.JPopupMenu();
        pmuRefressh = new javax.swing.JMenuItem();
        pmiCopy = new javax.swing.JMenuItem();
        pnlImage = new javax.swing.JPanel();
        lblImage = new javax.swing.JLabel();
        pnlButtons = new javax.swing.JPanel();
        btnLeftUp = new javax.swing.JButton();
        btnUp = new javax.swing.JButton();
        btnRightUp = new javax.swing.JButton();
        btnLeft = new javax.swing.JButton();
        btnHome = new javax.swing.JButton();
        btnRight = new javax.swing.JButton();
        btnLeftDown = new javax.swing.JButton();
        btnDown = new javax.swing.JButton();
        btnRightDown = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        mniConnect = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        mniExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        mniCopy = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        mniConfig = new javax.swing.JMenuItem();

        pumImage.setComponentPopupMenu(pumImage);

        pmuRefressh.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        pmuRefressh.setMnemonic('R');
        pmuRefressh.setText("Refrescar");
        pumImage.add(pmuRefressh);

        pmiCopy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        pmiCopy.setMnemonic('C');
        pmiCopy.setText("Copiar");
        pumImage.add(pmiCopy);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        pnlImage.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pnlImage.setMaximumSize(new java.awt.Dimension(640, 480));
        pnlImage.setMinimumSize(new java.awt.Dimension(640, 480));
        pnlImage.setPreferredSize(new java.awt.Dimension(640, 480));

        lblImage.setText("jLabel1");
        lblImage.setInheritsPopupMenu(false);

        javax.swing.GroupLayout pnlImageLayout = new javax.swing.GroupLayout(pnlImage);
        pnlImage.setLayout(pnlImageLayout);
        pnlImageLayout.setHorizontalGroup(
            pnlImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblImage, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
        );
        pnlImageLayout.setVerticalGroup(
            pnlImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblImage, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
        );

        lblImage.setText( "" );

        pnlButtons.setLayout(new java.awt.GridLayout(3, 3));

        btnLeftUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-leftUp.png"))); // NOI18N
        btnLeftUp.setActionCommand("0");
        btnLeftUp.setMaximumSize(new java.awt.Dimension(42, 42));
        btnLeftUp.setMinimumSize(new java.awt.Dimension(42, 42));
        btnLeftUp.setPreferredSize(new java.awt.Dimension(42, 42));
        btnLeftUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnLeftUp);

        btnUp.setFont(new java.awt.Font("Webdings", 1, 12)); // NOI18N
        btnUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-up.png"))); // NOI18N
        btnUp.setActionCommand("1");
        btnUp.setMaximumSize(new java.awt.Dimension(42, 42));
        btnUp.setMinimumSize(new java.awt.Dimension(42, 42));
        btnUp.setPreferredSize(new java.awt.Dimension(42, 42));
        btnUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnUp);

        btnRightUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-rightUp.png"))); // NOI18N
        btnRightUp.setActionCommand("2");
        btnRightUp.setMaximumSize(new java.awt.Dimension(42, 42));
        btnRightUp.setMinimumSize(new java.awt.Dimension(42, 42));
        btnRightUp.setPreferredSize(new java.awt.Dimension(42, 42));
        btnRightUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnRightUp);

        btnLeft.setFont(new java.awt.Font("Webdings", 1, 12)); // NOI18N
        btnLeft.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-left.png"))); // NOI18N
        btnLeft.setActionCommand("3");
        btnLeft.setMaximumSize(new java.awt.Dimension(42, 42));
        btnLeft.setMinimumSize(new java.awt.Dimension(42, 42));
        btnLeft.setPreferredSize(new java.awt.Dimension(42, 42));
        btnLeft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnLeft);

        btnHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/go-home.png"))); // NOI18N
        btnHome.setActionCommand("4");
        btnHome.setMaximumSize(new java.awt.Dimension(42, 42));
        btnHome.setMinimumSize(new java.awt.Dimension(42, 42));
        btnHome.setPreferredSize(new java.awt.Dimension(42, 42));
        btnHome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnHome);

        btnRight.setFont(new java.awt.Font("Webdings", 1, 12)); // NOI18N
        btnRight.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-right.png"))); // NOI18N
        btnRight.setActionCommand("5");
        btnRight.setMaximumSize(new java.awt.Dimension(42, 42));
        btnRight.setMinimumSize(new java.awt.Dimension(42, 42));
        btnRight.setPreferredSize(new java.awt.Dimension(42, 42));
        btnRight.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnRight);

        btnLeftDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-leftDown.png"))); // NOI18N
        btnLeftDown.setActionCommand("6");
        btnLeftDown.setMaximumSize(new java.awt.Dimension(42, 42));
        btnLeftDown.setMinimumSize(new java.awt.Dimension(42, 42));
        btnLeftDown.setPreferredSize(new java.awt.Dimension(42, 42));
        btnLeftDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnLeftDown);

        btnDown.setFont(new java.awt.Font("Webdings", 1, 12)); // NOI18N
        btnDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-down.png"))); // NOI18N
        btnDown.setActionCommand("7");
        btnDown.setMaximumSize(new java.awt.Dimension(42, 42));
        btnDown.setMinimumSize(new java.awt.Dimension(42, 42));
        btnDown.setPreferredSize(new java.awt.Dimension(42, 42));
        btnDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnDown);

        btnRightDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/camera/images/arrow-rightDown.png"))); // NOI18N
        btnRightDown.setActionCommand("8");
        btnRightDown.setMaximumSize(new java.awt.Dimension(42, 42));
        btnRightDown.setMinimumSize(new java.awt.Dimension(42, 42));
        btnRightDown.setPreferredSize(new java.awt.Dimension(42, 42));
        btnRightDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoveCam(evt);
            }
        });
        pnlButtons.add(btnRightDown);

        jMenu1.setMnemonic('A');
        jMenu1.setText("Archivo");

        mniConnect.setAction( foto );
        mniConnect.setMnemonic('C');
        mniConnect.setText("Conectar");
        jMenu1.add(mniConnect);
        jMenu1.add(jSeparator1);

        mniExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        mniExit.setMnemonic('S');
        mniExit.setText("Salir");
        mniExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniExitActionPerformed(evt);
            }
        });
        jMenu1.add(mniExit);

        menuBar.add(jMenu1);

        jMenu2.setMnemonic('E');
        jMenu2.setText("Editar");

        mniCopy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        mniCopy.setMnemonic('C');
        mniCopy.setText("Copiar");
        jMenu2.add(mniCopy);
        jMenu2.add(jSeparator2);

        mniConfig.setMnemonic('f');
        mniConfig.setText("Configuración");
        jMenu2.add(mniConfig);

        menuBar.add(jMenu2);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlImage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(pnlButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pnlImage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnMoveCam( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_btnMoveCam
        int tipo = Integer.parseInt( ( (JButton)evt.getSource()).getActionCommand() );
        try {
            sendPost( pan, tilt, tipo);
        } catch ( MalformedURLException ex ) {
            Logger.getLogger( MainFrame.class.getName() ).log( Level.SEVERE, null, ex );
        } catch ( IOException ex ) {
            Logger.getLogger( MainFrame.class.getName() ).log( Level.SEVERE, null, ex );
        }
    }//GEN-LAST:event_btnMoveCam

    private void mniExitActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_mniExitActionPerformed
        dispose();
    }//GEN-LAST:event_mniExitActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDown;
    private javax.swing.JButton btnHome;
    private javax.swing.JButton btnLeft;
    private javax.swing.JButton btnLeftDown;
    private javax.swing.JButton btnLeftUp;
    private javax.swing.JButton btnRight;
    private javax.swing.JButton btnRightDown;
    private javax.swing.JButton btnRightUp;
    private javax.swing.JButton btnUp;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JLabel lblImage;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem mniConfig;
    private javax.swing.JMenuItem mniConnect;
    private javax.swing.JMenuItem mniCopy;
    private javax.swing.JMenuItem mniExit;
    private javax.swing.JMenuItem pmiCopy;
    private javax.swing.JMenuItem pmuRefressh;
    private javax.swing.JPanel pnlButtons;
    private javax.swing.JPanel pnlImage;
    private javax.swing.JPopupMenu pumImage;
    // End of variables declaration//GEN-END:variables
}
